package yiwang.rememberdaka;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by tony on 16/5/4.
 */
public class AlarmReceiver extends BroadcastReceiver {

    private Context context = null;
    private String seesionKey;
    private Handler handler = new Handler();
    private String strCurrentTime;

    private OnLoginListener onLoginListener = new OnLoginListener() {

        private String strLog = "";

        @Override
        public void onLoginResult(boolean isLoginSuccess, String jsonObj) {
            SimpleDateFormat formatter =   new SimpleDateFormat("yyyy年MM月dd日    HH:mm:ss     ");
            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
            String strTime = formatter.format(curDate);

            if (!isLoginSuccess || isNullOrEmpty(jsonObj)) {
                strLog = "登录失败 " + strTime;
                CheckLog.saveCheckInfo2File(strLog);
                if(context != null){
                    Toast.makeText(context, "登录失败！", Toast.LENGTH_SHORT).show();
                }
            }

            seesionKey = parseLoginInfo(jsonObj);
            if(isNullOrEmpty(seesionKey)){
                if(context != null){
                    Toast.makeText(context, "服务器返回数据错误！", Toast.LENGTH_SHORT).show();
                }
            }

            if(!isLoginSuccess || isNullOrEmpty(jsonObj) || isNullOrEmpty(seesionKey)){
                handler.postDelayed(new Runnable(){
                    public void run() {
                        //再次登录
                        if(conformRules()){
                            login(onLoginListener);
                        }
                    }
                }, 30 * 1000);
            }else{
                //打卡
                check(Constant.CHECK_IN, onCheckListener);
            }
        }
    };

    private OnCheckListener onCheckListener = new OnCheckListener() {
        private String strLog = "";
        @Override
        public void onCheckResult(boolean isCheckSuccess, int checkType, String json) {
            SimpleDateFormat formatter =   new SimpleDateFormat(" yyyy年MM月dd日 HH:mm:ss ");
            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
            String strTime = formatter.format(curDate);

            if(!isCheckSuccess){
                strLog = (checkType == Constant.CHECK_IN ? "上班签到失败" : "下班签退失败") + strTime;
                CheckLog.saveCheckInfo2File(strLog);
                if(context != null){
                    Toast.makeText(context, strLog, Toast.LENGTH_SHORT).show();
                }
                return;
            }

            String result = parseCheckInfo(json);
            if(isNullOrEmpty(result)){
                strLog = (checkType == Constant.CHECK_IN ? "服务器返回数据错误!上班签到失败" : "服务器返回数据错误!下班签退失败") + strTime;
                CheckLog.saveCheckInfo2File(strLog);
                if(context != null){
                    Toast.makeText(context, strLog, Toast.LENGTH_SHORT).show();
                }
                return;
            }

            if(result.equals("success")){
                strLog = (checkType == Constant.CHECK_IN ? "上班签到成功" : "下班签退成功") + strTime;
                CheckLog.saveCheckInfo2File(strLog);
                if(context != null){
                    Toast.makeText(context, strLog, Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;

        if(conformRules()){
            login(onLoginListener);
        }
    }

    private void login(final OnLoginListener onLoginListener) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("method", "login");
        params.addBodyParameter("loginid", UserInfo.getUserName());
        params.addBodyParameter("password", UserInfo.getUserPassword());
        params.addBodyParameter("isneedmoulds", "1");
        params.addBodyParameter("client", "1");
        params.addBodyParameter("clientver", "6.0.6");
        params.addBodyParameter("udid", UserInfo.getIdentifyNum());//手机识别码
        params.addBodyParameter("token", "");
        params.addBodyParameter("clientos", "LMY48W");
        params.addBodyParameter("clientosver", Build.VERSION.RELEASE);
        params.addBodyParameter("clienttype", "android");
        params.addBodyParameter("language", "zh");
        params.addBodyParameter("country", "CN");
        params.addBodyParameter("authcode", "");
        params.addBodyParameter("dynapass", "");
        params.addBodyParameter("tokenpass", "");
        params.addBodyParameter("relogin", "0");
        params.addBodyParameter("clientuserid", "");

        if (onLoginListener == null)
            return;

        Constant.HTTP_UTILS.send(HttpRequest.HttpMethod.POST, Constant.URL, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException httpException, String arg1) {
                String exception = httpException.toString();
                String result = arg1;
                String strLog = "报错!!!! " + exception + " !!!! " + result + " !!!!";
                CheckLog.saveCheckInfo2File(strLog);
                onLoginListener.onLoginResult(false, null);
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String jsonResult = responseInfo.result;
                onLoginListener.onLoginResult(true, jsonResult);
            }
        });
    }

    private String parseLoginInfo(String json) {
        if (isNullOrEmpty(json))
            return null;

        String sessionKey = "";
        try {
            JSONTokener jsonTokener = new JSONTokener(json);
            JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
            sessionKey = jsonObject.optString("sessionkey");
        } catch (JSONException e) {
            e.printStackTrace();
        }finally {
            return sessionKey;
        }
    }

    private void check(final int checkTpye, final OnCheckListener onCheckListener){
        if(onCheckListener == null){
            return;
        }

        String address;
        try {
            address = URLEncoder.encode(Constant.USER_ADDRESS, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }

        RequestParams params = new RequestParams();
        params.addBodyParameter("method", "checkin");
        params.addBodyParameter("type", checkTpye == Constant.CHECK_IN ? "checkin" : "checkout");
        params.addBodyParameter("latlng", "31.201415,121.581484");
        params.addBodyParameter("addr", address);
        params.addBodyParameter("sessionkey",seesionKey);

        String checkt = ((checkTpye == Constant.CHECK_IN) ? "checkin" : "checkout");

        String url = Constant.URL + "?"+"method=checkin"+"&type="+checkt
                +"&latlng=31.201407,121.581486"
                +"&addr="+address
                +"&sessionkey="+seesionKey;

        Constant.HTTP_UTILS.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException httpException, String arg1) {
                onCheckListener.onCheckResult(false, checkTpye, null);
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String jsonResult = responseInfo.result;
                onCheckListener.onCheckResult(true, checkTpye, jsonResult);
            }
        });
    }

    private String parseCheckInfo(String json){
        if (json == null)
            return null;

        String result = "";
        try {
            JSONTokener jsonTokener = new JSONTokener(json);
            JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
            result = jsonObject.optString("result");
        } catch (JSONException e) {
            e.printStackTrace();
        }finally {
            return result;
        }
    }


    private boolean conformRules(){
        Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int date = c.get(Calendar.DATE);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);

        strCurrentTime = year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second;
        System.out.println(strCurrentTime);

        if(hour == 8 && minute > 5 && minute <= 59){ //9点20分前可以打卡
            return true;
        }

        return false;
    }

    private static boolean isNullOrEmpty(String str) {
        return str == null || str.trim().length() == 0 || "null".equals(str);
    }


}
